import ResizeObserver from 'resize-observer-polyfill';
import type { Ref } from 'vue';
import { onBeforeUnmount, onMounted, ref } from 'vue';

export function useResize(componentRef: Ref, resizeCallback?: (rect: any) => void) {
  const rect = ref();
  let resizeObserver: any;
  onMounted(() => {
    resizeObserver = new ResizeObserver(entries => {
      entries.forEach(entry => {
        rect.value = entry.contentRect;
        if (typeof resizeCallback === 'function') {
          resizeCallback(rect.value);
        }
      });
    });

    if (componentRef.value) {
      resizeObserver.observe(componentRef.value);
    }
  });
  onBeforeUnmount(() => {
    if (resizeObserver) {
      resizeObserver.disconnect();
    }
  });

  return rect;
}
